//
// Last.fm Radio Tuner for DivX Connected
//

loadScript("md5.js");
loadScript("lastfmlib.js");
		
//Ping Stat Server
statFeedNo=210;   //210 is the plug-in number for Last Fm
loadScript("http://myDivXConnected.com/pMaker/includes/statsPush.js");
/////

  
		
var lfm = null;
var curLastFmUrl = "";

// Last.fm username (TODO: create interactive username selector with new keyboard-based edit control)
var user = "";

var playMonitorTimer = 0;

function onPlayMonitorTimer()
{
	if(!connected.playback.isAudioPlaying())
		playNextSong();
}

function startPlayMonitorTimer()
{
	if(playMonitorTimer == 0)
		playMonitorTimer = setInterval("onPlayMonitorTimer()", 1000);
}

function clearPlayMonitorTimer()
{
	if(playMonitorTimer != 0)
	{
		clearInterval(playMonitorTimer);
		playMonitorTimer = 0;
	}
}

function setStatus(status)
{
	var dctk = connected.toolkit;
	var statusText = dctk.getElementById("statusText");
	statusText.text = status;
}

function playNextSong()
{
	var obj = lfm.getCurrentTrack();
	if(obj == null)
		return;
	
	connected.playback.playFileURI(obj.location, "audio/mpeg");

	var dctk = connected.toolkit;
	var albumImg = dctk.getElementById("albumImg");
	var songTitle = dctk.getElementById("songTitle");
	var artistTitle = dctk.getElementById("artistTitle");
	var albumTitle = dctk.getElementById("albumTitle");
	
	var newAlbumImg = "";
	var newSongTitle = "";
	var newArtistTitle = "";
	var newAlbumTitle = "";
	
	if(obj.title)
		newSongTitle = obj.title;

	if(obj.album)
		newAlbumTitle = obj.album;

	if(obj.creator)
		newArtistTitle = obj.creator;

	if(obj.image)
		newAlbumImg = obj.image;

	albumImg.img.src = newAlbumImg;
	songTitle.text = newSongTitle;
	artistTitle.text = newArtistTitle;
	albumTitle.text = newAlbumTitle;
	
	lfm.popTrack();
	
	if(lfm.getCurrentTrack() == null)
		lfm.getPlaylist(null);

	startPlayMonitorTimer();			
}

function onPlaylist()
{
	playNextSong();
	
	setStatus("Now listening to: " + curLastFmUrl);
}

function onTune()
{
	connected.debug.print("Tune complete.");

	setStatus("Fetching playlist...");

	lfm.getPlaylist(onPlaylist);
}

function tune()
{
	if(curLastFmUrl != "")
	{
		connected.debug.print("Tuning to: " + curLastFmUrl + "...");
		lfm.startTune(curLastFmUrl, onTune);
		
		setStatus("Tuning to: " + curLastFmUrl + "...");
	}
}

function onLogin()
{
	setStatus("Logged in.");

	tune();
}

function onLoveComplete()
{
	connected.debug.print("LOVE successfully sent.");
}

function onLoveBtn()
{
	connected.debug.print("Sending LOVE command...");
	lfm.love(onLoveComplete);
}

function onBanComplete()
{
	connected.debug.print("BAN successfully sent.");
}

function onBanBtn()
{
	connected.debug.print("Sending BAN command...");
	lfm.ban(onBanComplete);

	playNextSong();
}

function onSkipComplete()
{
//			connected.debug.print("SKIP successfully sent.");
}

function onSkipBtn()
{
//			connected.debug.print("Sending SKIP command...");
//			lfm.skip(onSkipComplete);

	playNextSong();
}

function login()
{
	setStatus("Logging in...");
//			lfm.startLogin("connected_dev", "connected_dev", onLogin);
	lfm.startAnonymousLogin(onLogin);
}

function defaultButtonHandler(ev)
{
	var dctk = connected.toolkit;
	
	switch(ev.buttonId)
	{
		case dcIKeyEvent.BUTTON_ID_BACK:
		{
			if(window.history.length)
				window.history.back();
		}
		break;
	}
}

function onExpandMenuSelect(e)
{
	var dctk = connected.toolkit;
	dctk.dismissPopup();
	
	curLastFmUrl = e.item.id;
	
	if(lfm.getStatus() == LASTFM_STATUS_LOGGEDIN)
		tune();
}

function popupButtonHandler(ev)
{
	var dctk = connected.toolkit;

	switch(ev.buttonId)
	{
		case dcIKeyEvent.BUTTON_ID_BACK:
		{
			dctk.dismissPopup();
		}
		break;
	}
}

var genreTable = [	["Rock",       "lastfm://globaltags/rock"],
					["Blues",      "lastfm://globaltags/blues"],
					["Electronic", "lastfm://globaltags/electronic"],
					["Metal",      "lastfm://globaltags/metal"],
					["Country",    "lastfm://globaltags/country"],
					["Hip Hop",    "lastfm://globaltags/hip%20hop"],
					["Jazz",       "lastfm://globaltags/jazz"],
					["Pop",        "lastfm://globaltags/pop"]
				 ];

function showSelectorPanel()
{
	var dctk = connected.toolkit;
	
	var popup = dctk.createPanelCtrl("popup", true);

	popup.left = 0;
	popup.bottom = 0;
	popup.width = 580;
	popup.height = 400;
	
	var expandMenu = dctk.createExpandMenuCtrl("expandMenu", true);
	expandMenu.onSelect = onExpandMenuSelect;
	
	if(user != "")
	{
		var personalGroup = expandMenu.addGroup();
		personalGroup.text = "Personal Radio (" + user + ")";
		personalGroup.backgroundImg.src = "chrome://connected/content/button_enabled.png";
		personalGroup.backgroundImg.async = false;
	
		var item = personalGroup.addItem("lastfm://user/" + user + "/recommended/100");
		item.text = "My Recommendations";

		var item = personalGroup.addItem("lastfm://user/" + user + "/personal");
		item.text = "My Radio Station";

		var item = personalGroup.addItem("lastfm://user/" + user + "/playlist");
		item.text = "My Loved Tracks";

		var item = personalGroup.addItem("lastfm://user/" + user + "/neighbours");
		item.text = "My Neighbors";
	}
	
	var genreGroup = expandMenu.addGroup();
	genreGroup.text = "Tune by Genre";
	genreGroup.backgroundImg.src = "chrome://connected/content/button_enabled.png";
	genreGroup.backgroundImg.async = false;
	
	for(var i = 0; i < genreTable.length; i++)
	{
		var item = genreGroup.addItem(genreTable[i][1]);
		item.text = genreTable[i][0];
	}
	
	var maxExpandHeight = expandMenu.maxExpandHeight;

	popup.left = 640 * (1 / 4);
	popup.right = 640 * (4 / 5);
	popup.top = (480 + maxExpandHeight) / 2;
	popup.bottom = (480 - maxExpandHeight) / 2;
	popup.onUnhandledKeyEvent = popupButtonHandler;
	expandMenu.left = 0;
	expandMenu.bottom = 0;
	expandMenu.right = popup.width;
	expandMenu.top = popup.height;

	expandMenu.selectedItemTextColor = 0xFFE970;
	expandMenu.unselectedItemTextColor = 0x808080;
	expandMenu.itemBackgroundColor = 0x000000;

	popup.addChild(expandMenu);			

	dctk.invokePopup(popup);
}

function onPlayPauseBtn(e)
{
	if(connected.playback.isAudioPlaying())
	{
		clearPlayMonitorTimer();
		connected.playback.stopAudio();
	}
}

function onChangeStationBtn(e)
{
	showSelectorPanel();
}

function onLoadComplete()
{
	lfm = new lastFmSession();
	
	var dctk = connected.toolkit;

	dctk.logicalWidth = 640;
	dctk.logicalHeight = 480;
	
	var panel = dctk.createPanelCtrl("root", true);

	panel.left = 0;
	panel.bottom = 0;
	panel.width = 640;
	panel.height = 480;
	panel.filled = true;
	panel.color.rgb = 0xBCBEC0;
	
	var headerBackPanel = dctk.createPanelCtrl("headerBackPanel", true);
	headerBackPanel.filled = true;
	headerBackPanel.color.rgb = 0xD01F3C;
	headerBackPanel.left = 0;
	headerBackPanel.top = 480;
	headerBackPanel.right = 640;
	headerBackPanel.bottom = 400;
	panel.addChild(headerBackPanel);
	
	var logoImg = dctk.createImageCtrl("logoImg", true);
	logoImg.left = 10;
	logoImg.top = 470;
	logoImg.right = 180;
	logoImg.bottom = 410;
	logoImg.img.src = "badge_red_rev.gif";
	logoImg.mode = dctkImage.IMG_FILL;
	panel.addChild(logoImg);
	
	var mainBackImg = dctk.createImageCtrl("mainBackImg", true);
	mainBackImg.left = 0;
	mainBackImg.top = 400;
	mainBackImg.right = 640;
	mainBackImg.bottom = 360;
	mainBackImg.img.src = "gradient.gif";
	mainBackImg.mode = dctkImage.IMG_FILL;
	panel.addChild(mainBackImg);
	
	var mainPanel = dctk.createPanelCtrl("mainPanel", true);
	mainPanel.filled = true;
	mainPanel.color.rgb = 0xFFFFFF;
	mainPanel.outlined = true;
	mainPanel.left = 20;
	mainPanel.top = 380;
	mainPanel.right = 620;
	mainPanel.bottom = 150;
	panel.addChild(mainPanel);
	
	var albumImg = dctk.createImageCtrl("albumImg", true);
	albumImg.left = 10;
	albumImg.top = 220;
	albumImg.right = 220;
	albumImg.bottom = 10;
	mainPanel.addChild(albumImg);
	
	var songTitle = dctk.createLabelCtrl("songTitle", true);
	songTitle.left = 240;
	songTitle.top = 220;
	songTitle.right = 580;
	songTitle.bottom = 190;
	songTitle.textColor.rgb = 0x000000;
	songTitle.fontSize = 26;
	songTitle.ellipsis = dctkLabel.TS_POSTELLIPSIS;
	songTitle.multiline = false;
	mainPanel.addChild(songTitle);
	
	var artistTitle = dctk.createLabelCtrl("artistTitle", true);
	artistTitle.left = 240;
	artistTitle.top = 190;
	artistTitle.right = 580;
	artistTitle.bottom = 160;
	artistTitle.textColor.rgb = 0x000000;
	artistTitle.fontSize = 20;
	artistTitle.ellipsis = dctkLabel.TS_POSTELLIPSIS;
	artistTitle.multiline = false;
	mainPanel.addChild(artistTitle);
	
	var albumTitle = dctk.createLabelCtrl("albumTitle", true);
	albumTitle.left = 240;
	albumTitle.top = 145;
	albumTitle.right = 580;
	albumTitle.bottom = 115;
	albumTitle.textColor.rgb = 0x000000;
	albumTitle.fontSize = 20;
	albumTitle.ellipsis = dctkLabel.TS_POSTELLIPSIS;
	albumTitle.multiline = false;
	mainPanel.addChild(albumTitle);
	
	var statusPanel = dctk.createPanelCtrl("statusPanel", true);
	statusPanel.filled = true;
	statusPanel.color.rgb = 0xFFFFFF;
	statusPanel.outlined = true;
	statusPanel.left = 20;
	statusPanel.top = 130;
	statusPanel.right = 620;
	statusPanel.bottom = 100;
	panel.addChild(statusPanel);
	
	var statusText = dctk.createLabelCtrl("statusText", true);
	statusText.left = 0;
	statusText.top = 30;
	statusText.right = 600;
	statusText.bottom = 0;
	statusText.textColor.rgb = 0x000000;
	statusText.fontSize = 20;
	statusText.align = dctkLabel.TS_CENTER;
	statusText.valign = dctkLabel.TS_MIDDLE;
	statusPanel.addChild(statusText);
	
	var btnPanel = dctk.createPanelCtrl("btnPanel", true);
	btnPanel.filled = true;
	btnPanel.color.rgb = 0xAAAAAA;
	btnPanel.outlined = true;
	btnPanel.left = 20;
	btnPanel.top = 80;
	btnPanel.right = 620;
	btnPanel.bottom = 20;
	panel.addChild(btnPanel);
	
//			var loveBtn = dctk.createButtonCtrl("loveBtn", true);
//			loveBtn.left = 40;
//			loveBtn.right = 140;
//			loveBtn.top = 50;
//			loveBtn.bottom = 10;
//			loveBtn.text = "Love";
//			loveBtn.onSelect = onLoveBtn;
//			btnPanel.addChild(loveBtn);
//			
//			var banBtn = dctk.createButtonCtrl("banBtn", true);
//			banBtn.left = 160;
//			banBtn.right = 260;
//			banBtn.top = 50;
//			banBtn.bottom = 10;
//			banBtn.text = "Ban";
//			banBtn.onSelect = onBanBtn;
//			btnPanel.addChild(banBtn);
//			
	var btnSize = 16;
	var playPauseBtn = dctk.createButtonCtrl("playPauseBtn", true);
	playPauseBtn.left = 100;
	playPauseBtn.right = 220;
	playPauseBtn.top = 50;
	playPauseBtn.bottom = 10;
	playPauseBtn.text = "Stop";
	playPauseBtn.fontSize = btnSize;
	playPauseBtn.onSelect = onPlayPauseBtn;
	btnPanel.addChild(playPauseBtn);
	
	var changeStationBtn = dctk.createButtonCtrl("changeStationBtn", true);
	changeStationBtn.left = 240;
	changeStationBtn.right = 360;
	changeStationBtn.top = 50;
	changeStationBtn.bottom = 10;
	changeStationBtn.text = "Change Station";
	changeStationBtn.fontSize = btnSize;
	changeStationBtn.onSelect = onChangeStationBtn;
	btnPanel.addChild(changeStationBtn);
	
	var skipBtn = dctk.createButtonCtrl("skipBtn", true);
	skipBtn.left = 380;
	skipBtn.right = 500;
	skipBtn.top = 50;
	skipBtn.bottom = 10;
	skipBtn.text = "Skip";
	skipBtn.fontSize = btnSize;
	skipBtn.onSelect = onSkipBtn;
	btnPanel.addChild(skipBtn);

	dctk.rootPanel = panel;

	playPauseBtn.rightSibling = changeStationBtn;	
	changeStationBtn.leftSibling = playPauseBtn;	
	changeStationBtn.rightSibling = skipBtn;	
	skipBtn.leftSibling = changeStationBtn;	
	dctk.focusedElement = skipBtn;	

	panel.onUnhandledKeyEvent = defaultButtonHandler;
	
	login();
	showSelectorPanel();
}